package com.dcjt.firehotcarpad.fragment

import CarStatePool
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.util.ToastUtil
import com.aries.ui.view.radius.RadiusTextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.base.ApiPath
import com.dcjt.firehotcarpad.base.SPConstant
import com.dcjt.firehotcarpad.entity.BaseEntity
import com.dcjt.firehotcarpad.entity.CarCurrentDetailEntity
import com.dcjt.firehotcarpad.entity.FunEntity
import com.dcjt.firehotcarpad.model.FunctionViewModel
import com.dcjt.firehotcarpad.moudle.HandleDisasterActivity
import com.dcjt.firehotcarpad.utils.AlertDialogUtil
import com.dcjt.firehotcarpad.utils.LocationType
import com.dcjt.firehotcarpad.utils.MarkerToMapType
import com.flyco.tablayout.listener.OnTabSelectListener
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

/**
 * Created by cj on 2021/2/20.
 * Email:codesexy@163.com
 * Function:
 * desc:主页的左边的Fragment
 */
class MainOperationFragment : BaseTabsFragment() , CarStatePool.CarStateChangeObserver {

    var ywjq: Boolean? = null
    var mStop: Boolean? = null
    var jqid: String? = null
    var mAdapter : MainButtonAdapter? = null
    lateinit var rv_car_zt : RecyclerView
    lateinit var viewModel: FunctionViewModel

    override fun onResume() {
        super.onResume()
        mStop = false
    }

    @SuppressLint("CheckResult")
    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        bottomContainer.visibility = View.VISIBLE
        viewModel = ViewModelProvider(this).get(FunctionViewModel::class.java)

        val bottomView = View.inflate(requireContext(), R.layout.layout_main_bottom, null)
        rv_car_zt =  bottomView.findViewById<RecyclerView>(R.id.rv_car_zt)
        bottomContainer.addView(bottomView)

        CarStatePool.get().registerCarStateObserver(this)
        CarStatePool.get().getCarState(true)

        val list: ArrayList<FunEntity> = ArrayList()
        list.add(FunEntity("待命", true, false, LocationType.DAIMING))
        list.add(FunEntity("训练", true, false, LocationType.XUNLIAN))
        list.add(FunEntity("加油", true, false, LocationType.JIAYOU))
        list.add(FunEntity("公务", true, false, LocationType.WORK))
        mAdapter = MainButtonAdapter( list)
        rv_car_zt.setLayoutManager(GridLayoutManager(mContext, 4))
        rv_car_zt.setAdapter(mAdapter)
        mAdapter!!.notifyDataSetChanged()

        mAdapter!!.setOnItemClickListener(BaseQuickAdapter.OnItemClickListener { adapter, view, position ->
            val entity = mAdapter?.getItem(position)
            entity ?: return@OnItemClickListener
            if (entity != null)
                if (entity.enable) {
                    showTipAlert(entity.str,entity.btnCommand.flag)
                }
        })
        initLiveData()
    }

    private fun initLiveData() {
        viewModel.requestStatusLiveData.observeForever {
            if (it.code == BaseEntity.err) {
                ToastUtil.show("操作失败")
            } else {
                ToastUtil.show("操作成功")
                //主动请求刷新状态
                CarStatePool.get().getCarState(true)
            }
        }
    }

    /**
     * 修改状态提示框
     */
    fun showTipAlert(zt:String,ztdm :String){
        if(ywjq!= null){
            if (ywjq!!){
                AlertDialogUtil.alertTips(requireContext(),
                    resources.getString(R.string.tips), "您还有未处置完毕的警情，不可修改车辆状态为  ${zt}  ,立即前往处置？",
                    {
                        //
                    }, {
                        //确定
                        //进行网络请求---修改车辆状态
                        startActivityForResult(
                            Intent( mContext, HandleDisasterActivity::class.java).putExtra("jqid",jqid), ApiPath.REQUEST_CODE
                        )
                    }, negativeBtn = "取消", positiveBtn = "确定"
                )
            } else{
                //修改状态
                AlertDialogUtil.alertTips(requireContext(),
                    resources.getString(R.string.tips), "修改车辆状态为   ${zt} ？",
                    {
                        //
                    }, {
                        //确定
                        //进行网络请求---修改车辆状态
                        viewModel.changeCarStatus("","",ztdm, ywjq!!,mContext)
                    }, negativeBtn = "取消", positiveBtn = "确定"
                )
            }
        }

    }


    override fun getTabTitles(): List<String> =
        mContext.resources.getStringArray(R.array.main_arrays_title).toList()


    override fun getFragments(): List<Fragment> = mutableListOf(
        DisastersListFragment.newInstance(),
        WaterSourceFragment.newInstance(1),
//        WaterTabFragment.newInstance(""),
        InstructionListFragment()
    )


    override fun onDestroy() {
        super.onDestroy()
        CarStatePool.get().unRegisterCarStateObserver(this)
        mStop = true
    }

    override fun onCarStateChange(carStateDetail: CarCurrentDetailEntity) {
        //判断状态值

        ywjq = carStateDetail!!.clxx!!.ywjq!!
        jqid = carStateDetail!!.clxx!!.jqid!!
        var position:Int = -1
        when(carStateDetail.clxx!!.clzzzt){
            //待命
            "02" -> position = 0
            //训练
            "04" -> position=1
            //加油
            "05" -> position=2
            //公务
            "08" ->position =3
         }
        uploadAdpater(position)
        mAdapter?.notifyDataSetChanged()
    }

    private fun uploadAdpater(position: Int) {
        for (i in 0..3){
            mAdapter?.getItem(i)?.enable = position!=i
        }
    }
}


class MainButtonAdapter(data: List<FunEntity>?) :
    BaseQuickAdapter<FunEntity, BaseViewHolder>(R.layout.item_main_button, data) {

    override fun convert(helper: BaseViewHolder?, item: FunEntity?) {
        helper!!
        item!!
        val rtvText = helper.getView<RadiusTextView>(R.id.rtv_text)
        val delegate = rtvText.delegate
        rtvText.text = item.str
//


        if (!item.enable) {
            delegate.setBackgroundColor(mContext.resources.getColor(R.color.button_1))
            delegate.setTextColor(mContext.resources.getColor(R.color.button_2))
            delegate.setStrokeWidth(2)
            delegate.setStrokeColor(mContext.resources.getColor(R.color.button_3))
        }else{
            delegate.setBackgroundColor(mContext.resources.getColor(R.color.mainColor))
            delegate.setTextColor(Color.WHITE)
        }


    }
}